package com.authenticateCenter.factory;



import com.authenticateCenter.domain.dto.RoleDto;
import com.authenticateCenter.domain.entity.Role;
import com.authenticateCenter.domain.vo.RoleVo;
import com.security.domain.authority.CommonRole;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.factory.Mappers;

import java.util.ArrayList;
import java.util.List;

import static com.authenticateCenter.factory.AuthorityFactory.AUTHORITY_CONVERT;


/**
 * @author 大忽悠
 * @create 2022/10/8 22:18
 */
public class RoleFactory {
    public static RoleConverter ROLE_CONVERT = Mappers.getMapper(RoleConverter.class);

    @Mapper(uses = AuthorityFactory.AuthorityConverter.class)
    public interface RoleConverter{
        @Mapping(target = "authorityList",ignore = true)
        RoleVo toRoleVo(Role role);
        @Mapping(target = "id",ignore = true)
        Role toRole(RoleDto authorityDto);

        default List<CommonRole> toCommonRole(List<RoleVo> roleVo) {
            if (roleVo == null) {
                return null;
            } else {
                List<CommonRole> list = new ArrayList(roleVo.size());
                roleVo.forEach(rv->list.add(roleVoToCommonRole(rv)));
                return list;
            }
        }
        @Mapping(target = "authority",source = "name")
        CommonRole toCommonRole(Role role);
    }

    protected static CommonRole roleVoToCommonRole(RoleVo roleVo) {
        if (roleVo == null) {
            return null;
        } else {
            CommonRole.CommonRoleBuilder commonRole = CommonRole.builder();
            commonRole.authority(roleVo.getName());
            commonRole.allowedOperations(AUTHORITY_CONVERT.toListCommonAuthority(roleVo.getAuthorityList()));
            return commonRole.build();
        }
    }
}
